package com.wtg.gateway.userserver;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import com.wtg.gateway.util.JwtUtil;

import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
	
	// 令牌头名字
	private static final String AUTHORIZE_TOKEN = "Authorization";

	@Override
	public int getOrder() {
		return 0;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		  // 获取Request、Response对象
		  ServerHttpRequest request = exchange.getRequest();
		  ServerHttpResponse response = exchange.getResponse();
		  // 获取请求的URI
		  String path = request.getURI().getPath();
		  if (path.startsWith("/clientOne/product/get")) {
			  String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
			  // 如果头文件中没有令牌信息，则从请求参数中获取
			  if (StringUtils.isEmpty(token)) {
			   token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
			  }
			  // 如果为空，则输出错误代码
			  if (StringUtils.isEmpty(token)) {
			   // 设置方法不允许被访问，405错误代码
			   response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
			   return response.setComplete();
			  }
			  // 如果不为空，则解析令牌数据
			  try {
			   JwtUtil.parseJWT(token);
			  } catch (Exception e) {
			   e.printStackTrace();
			   // 解析失败，响应401错误
			   response.setStatusCode(HttpStatus.UNAUTHORIZED);
			   return response.setComplete();
			  }
			  // 放行之前，将令牌封装到头文件中(这一步是为了方便AUTH2校验令牌)
			  request.mutate().header(AUTHORIZE_TOKEN,token);
			  // 放行
			  return chain.filter(exchange);
		  }
		  // 放行
		  Mono<Void> filter = chain.filter(exchange);
		  return filter;
	}

}
